import pandas as pd
import numpy as np
from pyecharts import options as opts
from pyecharts.charts import WordCloud

class WordCloud_weather_all(): 
    
    def __init__(self, dataset, place=0):
        self.paint_data=dataset
        self.place=place #九寨沟——0；四姑娘山——1
        
        #主程序入口
        self.main()
    
    #主程序入口函数实现
    def main(self):
        
        # 调用获取数据函数
        self.getData()
        
        # 调用词云图绘制函数
        self.paintWordCloud()
        
    #获取数据
    def getData(self):
            
        weather=self.paint_data.loc[:,'weather'] #获取天气数据
        
        #统计数组中相同元素的数量
        def all_np(arr):
            arr = np.array(arr) #将数据转化为np数组
            key = np.unique(arr)
            result = {}
            for k in key:
                mask = (arr == k)
                arr_new = arr[mask]
                v = arr_new.size
                result[k] = v
            return result
        
        weather_nums=all_np(weather) #共有xx种天气
        self.paint_data=sorted(weather_nums.items(), key=lambda item:item[1],reverse = True) #将字典按values从高到低进行排序，生成的是list
        # print(self.paint_data)
        
    # 绘制词云图
    def paintWordCloud(self):
        
        if self.place==0:
            title='九寨沟2013-2016年天气词云图'
        else:
            title='小金2016-2019年天气词云图' 
        
        fileName='2.3 '+title+".html"
        
        words=self.paint_data
        
        '''
        c = (
            WordCloud()
            .add("", words, word_size_range=[20, 100], shape=SymbolType.DIAMOND)
            .set_global_opts(title_opts=opts.TitleOpts(title=title))
            .render(title+".html")
        )
        '''
        (
            WordCloud(init_opts=opts.InitOpts(width="900px", height="600px"))
            .add(series_name=title, data_pair=words, word_size_range=[20, 100])
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=title, title_textstyle_opts=opts.TextStyleOpts(font_size=23)
                ),
                tooltip_opts=opts.TooltipOpts(is_show=True),
            )
            .render('resultFile/'+fileName)
        )
        
        print(fileName+'已生成！')
   
        
        
        
        